package main.链表;

import common.ListNode;

/**
 * @author tmh
 * @date 2024/7/20 14:36
 * @description
 */
public class T19删除链表的倒数第N个结点 {
    //需要定义一个虚拟节点dummy来进行操作,然后定义cur来指向dummy
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        //得到链表的长度
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        //让dummy移动到要删除节点的前一个节点
        for (int i = 1; i < length - n + 1; i++) {
            dummy=dummy.next;
        }
        dummy.next=dummy.next.next;
        return cur.next;
    }
}
